const router = require("express").Router();
const sql = require("../mysql");
const Customer = require("../mysql/collection/Customer");
const User = require("../mysql/collection/User");
const Order = require("../mysql/collection/Order");
const Opportunity = require("../mysql/collection/Opportunity");
const uuid = require("uuid");

/**
 * @api {POST} /admin/crm/integration/sync-users 同步用户数据到CRM客户
 * @apiName SyncUsersToCustomers
 * @apiGroup CRM-Integration
 *
 * @apiParam {Array} [userIds] 指定用户ID列表，不传则同步所有用户
 * @apiParam {Boolean} [overwrite=false] 是否覆盖已存在的客户数据
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 同步结果
 * @apiSuccess {Number} data.total 总用户数
 * @apiSuccess {Number} data.synced 成功同步数
 * @apiSuccess {Number} data.skipped 跳过数
 * @apiSuccess {Array} data.errors 错误列表
 */
router.post("/integration/sync-users", async (req, res) => {
  try {
    const { userIds, overwrite = false } = req.body;
    let query = {};
    if (userIds && userIds.length > 0) {
      query.userid = { $in: userIds };
    }
    
    const users = await User.find(query);
    let synced = 0;
    let skipped = 0;
    let errors = [];
    
    for (const user of users) {
      try {
        // 检查是否已存在对应的客户
        const existingCustomer = await Customer.findOne({ 
          $or: [
            { phone: user.tel },
            { email: user.email }
          ]
        });
        
        if (existingCustomer && !overwrite) {
          skipped++;
          continue;
        }
        
        const customerData = {
          customerId: user.userid || uuid.v4(),
          name: user.nickname || user.username || '未知用户',
          phone: user.tel || '',
          email: user.email || '',
          source: '网站',
          status: '潜在客户',
          assignedTo: req.user.adminid,
          tags: ['系统同步'],
          notes: `从用户系统同步，原用户ID: ${user.userid}`,
          createTime: user.createTime || new Date()
        };
        
        if (existingCustomer && overwrite) {
          await Customer.findByIdAndUpdate(existingCustomer._id, customerData);
        } else {
          await Customer.create(customerData);
        }
        
        synced++;
      } catch (error) {
        errors.push({
          userId: user.userid,
          error: error.message
        });
      }
    }
    
    res.send({
      code: "200",
      message: "用户数据同步完成",
      data: {
        total: users.length,
        synced,
        skipped,
        errors
      }
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "用户数据同步失败",
      error: error.message
    });
  }
});

/**
 * @api {POST} /admin/crm/integration/create-opportunities-from-orders 从订单创建商机
 * @apiName CreateOpportunitiesFromOrders
 * @apiGroup CRM-Integration
 *
 * @apiParam {Array} [orderIds] 指定订单ID列表，不传则处理所有已完成订单
 * @apiParam {Number} [minAmount=0] 最小订单金额筛选
 * @apiParam {Boolean} [onlyCompleted=true] 是否只处理已完成订单
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 创建结果
 */
router.post("/integration/create-opportunities-from-orders", async (req, res) => {
  try {
    const { orderIds, minAmount = 0, onlyCompleted = true } = req.body;
    let query = {};
    
    if (orderIds && orderIds.length > 0) {
      query.orderid = { $in: orderIds };
    }
    
    if (onlyCompleted) {
      query.status = 4; // 已完成状态
    }
    
    const orders = await Order.find(query);
    let created = 0;
    let skipped = 0;
    let errors = [];
    
    for (const order of orders) {
      try {
        const orderAmount = order.discount * order.num;
        if (orderAmount < minAmount) {
          skipped++;
          continue;
        }
        
        // 查找对应的客户
        const customer = await Customer.findOne({ 
          $or: [
            { phone: order.tel },
            { customerId: order.userid }
          ]
        });
        
        if (!customer) {
          errors.push({
            orderId: order.orderid,
            error: '未找到对应客户'
          });
          continue;
        }
        
        // 检查是否已存在对应的商机
        const existingOpportunity = await Opportunity.findOne({
          title: { $regex: order.orderid, $options: 'i' }
        });
        
        if (existingOpportunity) {
          skipped++;
          continue;
        }
        
        const opportunityData = {
          opportunityId: uuid.v4(),
          customerId: customer._id,
          title: `订单商机 - ${order.proname}`,
          description: `基于订单 ${order.orderid} 创建的商机`,
          value: orderAmount,
          stage: '已成交',
          status: '进行中',
          probability: 100,
          expectedCloseDate: new Date(order.time),
          assignedTo: req.user.adminid,
          createTime: new Date(order.time)
        };
        
        await Opportunity.create(opportunityData);
        created++;
      } catch (error) {
        errors.push({
          orderId: order.orderid,
          error: error.message
        });
      }
    }
    
    res.send({
      code: "200",
      message: "订单商机创建完成",
      data: {
        total: orders.length,
        created,
        skipped,
        errors
      }
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "订单商机创建失败",
      error: error.message
    });
  }
});

/**
 * @api {GET} /admin/crm/integration/customer-orders/:customerId 获取客户订单历史
 * @apiName GetCustomerOrders
 * @apiGroup CRM-Integration
 *
 * @apiParam {String} customerId 客户ID
 * @apiParam {Number} [page=1] 页码
 * @apiParam {Number} [pageSize=10] 每页数量
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 订单数据
 */
router.get("/integration/customer-orders/:customerId", async (req, res) => {
  try {
    const { page = 1, pageSize = 10 } = req.query;
    const skip = (page - 1) * pageSize;
    
    const customer = await Customer.findById(req.params.customerId);
    if (!customer) {
      return res.send({
        code: "404",
        message: "客户不存在"
      });
    }
    
    // 通过电话号码或客户ID查找订单
    const query = {
      $or: [
        { tel: customer.phone },
        { userid: customer.customerId }
      ]
    };
    
    const total = await Order.countDocuments(query);
    const orders = await Order.find(query)
      .sort({ time: -1 })
      .skip(skip)
      .limit(parseInt(pageSize));
    
    // 计算订单统计
    const allOrders = await Order.find(query);
    const stats = {
      totalOrders: allOrders.length,
      totalAmount: allOrders.reduce((sum, order) => sum + (order.discount * order.num), 0),
      completedOrders: allOrders.filter(order => order.status === 4).length,
      avgOrderValue: allOrders.length > 0 ? 
        allOrders.reduce((sum, order) => sum + (order.discount * order.num), 0) / allOrders.length : 0
    };
    
    res.send({
      code: "200",
      message: "获取客户订单历史成功",
      data: {
        orders,
        stats,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "获取客户订单历史失败",
      error: error.message
    });
  }
});

/**
 * @api {GET} /admin/crm/integration/user-profile/:userId 获取用户CRM档案
 * @apiName GetUserCRMProfile
 * @apiGroup CRM-Integration
 *
 * @apiParam {String} userId 用户ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 用户CRM档案
 */
router.get("/integration/user-profile/:userId", async (req, res) => {
  try {
    const user = await User.findOne({ userid: req.params.userId });
    if (!user) {
      return res.send({
        code: "404",
        message: "用户不存在"
      });
    }
    
    // 查找对应的CRM客户
    const customer = await Customer.findOne({
      $or: [
        { phone: user.tel },
        { email: user.email },
        { customerId: user.userid }
      ]
    }).populate('assignedTo', 'adminname');
    
    // 查找用户订单
    const orders = await Order.find({ userid: user.userid }).sort({ time: -1 });
    
    // 查找相关商机
    let opportunities = [];
    if (customer) {
      opportunities = await Opportunity.find({ customerId: customer._id })
        .populate('assignedTo', 'adminname')
        .sort({ createTime: -1 });
    }
    
    const profile = {
      user: {
        userid: user.userid,
        username: user.username,
        nickname: user.nickname,
        tel: user.tel,
        email: user.email,
        createTime: user.createTime
      },
      customer: customer || null,
      orderStats: {
        totalOrders: orders.length,
        totalAmount: orders.reduce((sum, order) => sum + (order.discount * order.num), 0),
        completedOrders: orders.filter(order => order.status === 4).length,
        recentOrders: orders.slice(0, 5)
      },
      opportunities: opportunities.slice(0, 5),
      crmStatus: customer ? '已转换为客户' : '未转换为客户'
    };
    
    res.send({
      code: "200",
      message: "获取用户CRM档案成功",
      data: profile
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "获取用户CRM档案失败",
      error: error.message
    });
  }
});

/**
 * @api {POST} /admin/crm/integration/convert-user-to-customer 将用户转换为CRM客户
 * @apiName ConvertUserToCustomer
 * @apiGroup CRM-Integration
 *
 * @apiParam {String} userId 用户ID
 * @apiParam {String} [assignedTo] 指定负责人
 * @apiParam {Array} [tags] 客户标签
 * @apiParam {String} [notes] 备注信息
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 创建的客户数据
 */
router.post("/integration/convert-user-to-customer", async (req, res) => {
  try {
    const { userId, assignedTo, tags = [], notes = '' } = req.body;
    
    const user = await User.findOne({ userid: userId });
    if (!user) {
      return res.send({
        code: "404",
        message: "用户不存在"
      });
    }
    
    // 检查是否已转换
    const existingCustomer = await Customer.findOne({
      $or: [
        { phone: user.tel },
        { email: user.email },
        { customerId: user.userid }
      ]
    });
    
    if (existingCustomer) {
      return res.send({
        code: "400",
        message: "该用户已转换为客户",
        data: existingCustomer
      });
    }
    
    const customerData = {
      customerId: user.userid,
      name: user.nickname || user.username || '未知用户',
      phone: user.tel || '',
      email: user.email || '',
      source: '网站',
      status: '潜在客户',
      assignedTo: assignedTo || req.user.adminid,
      tags: [...tags, '用户转换'],
      notes: notes || `从用户系统转换，原用户ID: ${user.userid}`
    };
    
    const customer = await Customer.create(customerData);
    const populatedCustomer = await Customer.findById(customer._id)
      .populate('assignedTo', 'adminname');
    
    res.send({
      code: "200",
      message: "用户转换为客户成功",
      data: populatedCustomer
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "用户转换为客户失败",
      error: error.message
    });
  }
});

module.exports = router;